import csv
from io import StringIO
from ..models import DevEnvironmentImage
from ..baseapp import db, OperationalError
from sqlalchemy.exc import IntegrityError


def create_dev_env_img(name, img_tag, description, git_repositories, editor_type):
    try:
        new_env = DevEnvironmentImage(
            name=name,
            img_tag=img_tag,
            editor_type=editor_type,
            description=description,
            git_repositories=git_repositories,
        )
        db.session.add(new_env)
        db.session.commit()
        return new_env
    except Exception as e:
        db.session.rollback()
        raise OperationalError(str(e))


def get_dev_env_img_by_id(env_id) -> DevEnvironmentImage | None:
    return DevEnvironmentImage.query.get(env_id)


def get_all_dev_env_imgs():
    return DevEnvironmentImage.query.all()


def update_dev_env_img(
    env_id,
    name=None,
    img_tag=None,
    editor_type=None,
    description=None,
    git_repositories=None,
):
    env = DevEnvironmentImage.query.get(env_id)
    if not env:
        return None
    if name is not None:
        env.name = name
    if img_tag is not None:
        env.img_tag = img_tag
    if description is not None:
        env.description = description
    if editor_type is not None:
        env.editor_type = editor_type
    if git_repositories is not None:
        env.git_repositories = git_repositories
    db.session.commit()
    return env


def delete_dev_env_img(env_id):
    env = DevEnvironmentImage.query.get(env_id)
    if not env:
        return False
    db.session.delete(env)
    db.session.commit()
    return True


def export_dev_env_imgs_to_csv():
    envs = DevEnvironmentImage.query.all()
    output = StringIO()
    writer = csv.writer(output)
    writer.writerow(
        ["id", "name", "img_tag", "description", "git_repositories", "editor_type"]
    )
    for env in envs:
        writer.writerow(
            [
                env.id,
                env.name,
                env.img_tag,
                env.description,
                env.git_repositories,
                env.editor_type,
            ]
        )
    output.seek(0)
    return output.getvalue()


def import_dev_env_imgs_from_csv(csv_data):

    input = StringIO(csv_data)
    reader = csv.DictReader(input)
    for row in reader:
        # Skip if the name already exists
        if DevEnvironmentImage.query.filter_by(name=row["name"]).first():
            continue
        new_env = DevEnvironmentImage(
            name=row["name"],
            img_tag=row["img_tag"],
            editor_type=row["editor_type"],
            description=row["description"],
            git_repositories=row["git_repositories"],
        )
        db.session.add(new_env)
    db.session.commit()
    return True
